/*
 * C Implementation: get_product_kind
 *
 * Description: how to process a file containing a mix of messages
 *              and print the kind of product (e.g. GRIB, BUFR etc)
 * 
 * 如何处理包含混合消息的文件，
 * 并打印产品种类
 * 
 */
#include "eccodes.h"

static void usage(const char* app)
{
    fprintf(stderr, "Usage: %s file\n", app);
}



int sfx_get_product_kind_0(int argc, char* argv[])
{
    int err = 0;

    printf("fksd\n");

    if (argc < 2) {
        usage(argv[0]);
        exit(0);
    }

    // char* fname = "D:\\sfxData\\ECMWF\\20200812\\era5-levels-members.grib";
    char* fname = argv[1];

    FILE* in = fopen(fname, "rb");
    if (!in) {
        fprintf(stderr, "Error: unable to open file %s\n", fname);
        exit(1);
    }

    int cnt         = 0;
    size_t len      = 0;
    char* kind      = NULL;
    codes_handle* h = NULL;

    while ((h = codes_handle_new_from_file(NULL, in, PRODUCT_ANY, &err)) != NULL || err != CODES_SUCCESS) {
        if (h == NULL) {
            fprintf(stderr, "Error: unable to create handle for message %d\n", cnt);
            cnt++;
            continue;
        }

        //
        long edition = 0;
        CODES_CHECK(codes_get_long(h, "edition", &edition), 0);

        // 取得消息类型
        CODES_CHECK(codes_get_length(h, "kindOfProduct", &len), 0);
        kind = (char*)malloc(len * sizeof(char));
        codes_get_string(h, "kindOfProduct", kind, &len);

        printf("[message %03d]: product kind = %s, edition = %d\n", cnt, kind, edition);

        free(kind);
        codes_handle_delete(h);
        cnt++;
    }

    fclose(in);
    return 0;
}


int sfx_get_product_kind(int argc, char* argv[])
{
    int err = 0;

    printf("fksd\n");

    if (argc < 2) {
        usage(argv[0]);
        exit(0);
    }

    // char* fname = "D:\\sfxData\\ECMWF\\20200812\\era5-levels-members.grib";
    char* fname = argv[1];

    FILE* in = fopen(fname, "rb");
    if (!in) {
        fprintf(stderr, "Error: unable to open file %s\n", fname);
        exit(1);
    }

    int cnt         = 0;
    size_t len      = 0;
    char* kind      = NULL;
    codes_handle* h = NULL;

    while ((h = codes_handle_new_from_file(NULL, in, PRODUCT_ANY, &err)) != NULL || err != CODES_SUCCESS) {
        if (h == NULL) {
            fprintf(stderr, "Error: unable to create handle for message %d\n", cnt);
            cnt++;
            continue;
        }

        //
        long edition = 0;
        CODES_CHECK(codes_get_long(h, "edition", &edition), 0);

        // 取得消息类型
        CODES_CHECK(codes_get_length(h, "kindOfProduct", &len), 0);
        kind = (char*)malloc(len * sizeof(char));
        codes_get_string(h, "kindOfProduct", kind, &len);

        printf("[message %03d]: product kind = %s, edition = %d\n", cnt, kind, edition);

        free(kind);
        codes_handle_delete(h);
        cnt++;
    }

    fclose(in);
    return 0;
}


